from rest_framework import serializers
from api import models


class ArticleSerializer(serializers.ModelSerializer):
    # 同名 覆盖原字段名
    # 外键关系引用
    category = serializers.CharField(source='category.name')
    # 方法自定义字段 SerializerMethodField
    Method_x1 = serializers.SerializerMethodField()
    # choices关系，get_xxxx_display.
    status_choices = serializers.CharField(source='get_status_display')
    # get_xxxx_display() 方法
    display_x2 = serializers.SerializerMethodField()
    # 日期格式format
    date = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S")
    author = serializers.CharField(source='author.username')
    # 反向关系引用 小写关系表名
    content = serializers.CharField(source='articledetail.content')
    # ToMany关系引用
    tag = serializers.SerializerMethodField()

    class Meta:
        model = models.Article
        fields = "__all__"
        # depth = 1

    def get_Method_x1(self, obj):
        return obj.category.name

    def get_display_x2(self, obj):
        return obj.get_status_display()

    def get_tag(self, obj):
        """ToMany关系引用方法，列表推导式"""
        # return [row for row in obj.tag.all().values('id', 'title')]
        return [row for row in obj.tag.values()]


# 为POST添加书籍专门 写个序列化器
class FormNewArticleSerializer(serializers.ModelSerializer):
    # 不需要提供author 登录状态中取
    author = serializers.CharField(source='author.username', help_text='作者', required=False)

    class Meta:
        model = models.Article
        fields = '__all__'


class ArticleDetailSerializer(serializers.ModelSerializer):
    """书籍详情"""
    # 不需要提供aarticle 新增的文章id中取值加入
    article = serializers.CharField(source='article.id', required=False, help_text='文章号')

    class Meta:
        model = models.ArticleDetail
        fields = '__all__'
